# encoding: UTF-8

from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
from sparkai.core.messages import ChatMessage
from sparkai.core.callbacks import StdOutCallbackHandler


def xunfei_chat(content, length, XF_APP_ID, XF_APP_KEY, XF_APP_SECRET, XF_LLM_DOMAIN):
    if not content:
        return "内容识别为空"
    print(content)
    print(length)
    spark = ChatSparkLLM(
        spark_api_url="wss://spark-api.xf-yun.com/v3.5/chat",
        spark_app_id=XF_APP_ID,
        spark_api_key=XF_APP_KEY,
        spark_api_secret=XF_APP_SECRET,
        spark_llm_domain=XF_LLM_DOMAIN,
        streaming=False,
    )
    if length > 0:
        content = f"请在{length}字内描述下{content}"
    messages = [ChatMessage(
        role="user",
        content=content
    )]
    handler = ChunkPrintHandler()
    a = spark.generate([messages], callbacks=[handler])
    result = a.generations[0][0].text
    return result
